package main

import (
	"fmt"
	"gitee.com/sdzxq/api_server/conf"
	"gitee.com/sdzxq/api_server/database"
	"gitee.com/sdzxq/api_server/models"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)



func sayHello( c *gin.Context) {
	c.JSON(200, gin.H{
		"message":"欢迎来到我们的v1版接口,请尽情享用接口服务！",
	})
}

func sayNo (c *gin.Context) {
	c.JSON(400, gin.H{
		"message":"本接口不提供服务",
	})
}

func dbStatus (c *gin.Context) {
	if database.TestDbConnect() {
		c.JSON(200, gin.H{
			"success": true,
			"message": "DB is Connected",
		})
	} else {
		c.JSON(500, gin.H{
			"success": false,
			"message": "DB Server is not reachable",
		})
	}
}

func getToken (c *gin.Context) {
	var jsonKey models.UserToken
	var addr = c.Request.RemoteAddr
	fmt.Println(addr)
	if err := c.ShouldBindJSON(&jsonKey); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error": err.Error(),
		})
		return
	}
	if jsonKey.Username != "mainzxq" || jsonKey.Pwd != "123" {
		c.JSON(http.StatusUnauthorized, gin.H{
			"success": false,
			"error": "unauthorized",
		})
		return
	}

	token, err := getOneToken(jsonKey.Username,addr,1,2,2)
	if err != nil {
		log.Fatal(err)
	}
	c.JSON(200, gin.H{
		"message":token,
		"username": jsonKey.Username,
		"pwd": jsonKey.Pwd,
		"addr": addr,
	})
}





func getOneToken(un string, addr string, authlvl int, syslvl int, adminlvl int) (string, error) {
	claim := models.SignClaim {
		un,
		addr,
		authlvl,
		syslvl,
		adminlvl,
		jwt.StandardClaims{
			//ExpiresAt: 15000,
			Issuer: un,
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)

	tokenStr, err := token.SignedString(conf.Secret)
	if err != nil {
		log.Fatal(err)
		return "", err
	}
	return tokenStr, nil
}

func getOneUser(c *gin.Context) {
	name := c.Param("id")
	var jsonkey, err = database.FindOneUser(name)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success":false,
			"error": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "info delivered!",
		"data": jsonkey,
	})
}


func createOneUser(c *gin.Context) {
	var jsonKey  models.User
	if err := c.ShouldBindJSON(&jsonKey); err != nil {
		fmt.Println(jsonKey)
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "接口处理错误！",
			"errors": err.Error(),
		})
		return
	}

	if find, err := database.FindOneUser(jsonKey.UserID); err == nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"message": "已有同名用户",
			"success": false,
			"errors": fmt.Sprintf("user existed: name=%s uid=%s",find.Username, find.UserID),
		})
	}

	res, err := database.CreateUser(jsonKey)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "数据库错误",
			"error": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": res,
		"message": "Create a new user!",
	})
}